﻿//子路由
let express = require("express"); //绝对路径
const axios = require('axios'); //准备用于发送ajax请求
const {
  ObjectId
} = require("mongodb");
//创建路由对象
let Router = express.Router(); //Router==app
let mongo = require("../../db/mongo");
let {
  create,
  verify
} = require("./token"); //引入jsonwebtoken插件
/*
  用户管理：restful接口规范
    * 验证用户名是否存在 ：get
    * 注册 : post 
    * 登录 : get 生成token 下一次:验证token
    * 删除用户 : delete
    * 查询用户列表 :get
    * 修改用户信息 :put
*/

//1.验证用户名是否存在
//访问该接口: /user/checkname
Router.get("/checkname", async (req, res) => {
  let result = {};
  // console.log(req.query);
  try {
    // let data = await mongo.lowfind("users", req.query);//方法一
    let data = await mongo.find("users", {
      findquery: req.query
    }); //方法一
    // console.log(data);

    if (data.code) {
      //验证有:不能注册
      result = {
        code: 0,
        message: "不能注册,用户已存在",
      };
    } else {
      result = {
        code: 1,
        message: "允许注册",
      };
    }
  } catch (err) {
    result = {
      code: 0,
      message: "服务器异常",
    };
  }
  res.send(result); //响应数据给前端
});

//2.注册
Router.post("/reg", async (req, res) => {
  //post请求 body
  // console.log(req.body);
  let arr = [];
  let result = {};
  arr.push(req.body);
  // console.log(arr,890);
  try {
    let data = await mongo.create("users", arr); //因为插入到数据库里面的数据必须是数组格式：arr是一个数组
    // console.log(data,789);
    if (data.code) {
      // let query = {username:req.body.username};
      // let res = await mongo.find("users", { findquery:  query});
      // console.log(res,666); 
      result = {
        code: 1,
        message: "注册成功",
        // uid : res.data[0]._id
      };
    } else {
      result = {
        code: 0,
        message: "注册失败",
      };
    }
  } catch (err) {
    result = {
      code: 0,
      message: "服务器异常",
    };
  }

  res.send(result); //响应数据给前端
});

//3.登录
Router.get("/login", async (req, res) => {
  let result = {};
  // console.log(req.query);
  try {
    let data = await mongo.find("users", {
      findquery: req.query
    }); //因为插入到数据库里面的数据必须是数组格式：arr是一个数组
    // console.log(data, 9999);
    if (data.code) {
      //登录成功
      //生成token
      let token = create(req.query.password);
      result = {
        code: 1,
        message: "登录成功",
        token,
        uid: data.data[0]._id
      };
    } else {
      result = {
        code: 0,
        message: "账号或密码错误",
      };
    }
  } catch (err) {
    result = {
      code: 0,
      message: "服务器异常",
    };
  }
  // res.send("登录成功");
  res.send(result); //响应数据给前端
});

//4.验证token:用在前端的路由守卫里面==路由拦截
Router.get("/verify", (req, res) => {
  let {
    token
  } = req.query; //前端传过来的token
  let result = {};
  let data = verify(token);
  if (data) {
    //校验通过
    result = {
      code: 1,
      message: "token校验通过",
    };
  } else {
    //校验失败
    result = {
      code: 0,
      message: "token校验不通过",
    };
  }
  res.send(result); //校验响应给前端
});

//5.删除用户
Router.delete("/del/:_id", async (req, res) => {
  // console.log(req.params);
  let _id = ObjectId(req.params._id);
  // console.log(_id);
  let query = {
    _id,
  }; //{_id:ObjectId(5f51a143db619cff3c548934)}
  let result = {};
  try {
    let data = await mongo.remove("users", query); //因为插入到数据库里面的数据必须是数组格式：arr是一个数组
    // console.log(data);
    if (data.code) {
      //登录成功
      //生成token
      result = {
        code: 1,
        message: "删除成功",
      };
    } else {
      result = {
        code: 0,
        message: "删除失败",
      };
    }
  } catch (err) {
    result = {
      code: 0,
      message: "服务器异常",
    };
  }
  // res.send("登录成功");
  res.send(result); //响应数据给前端
  // res.send("2323");
});

//6.查询用户列表
Router.get("/list", async (req, res) => {
  //用户传：page:1 页码；pagesize:10;过来
  console.log(req.query);
  let query = {
    page: req.query.page - 0,
    pagesize: req.query.pagesize * 1,
  };
  let result = {};
  try {
    let data = await mongo.find("users", query); //因为插入到数据库里面的数据必须是数组格式：arr是一个数组
    // console.log(data);
    result = data;
  } catch (err) {
    result = {
      code: 0,
      message: "服务器异常",
    };
  }
  // res.send("登录成功");
  res.send(result); //响应数据给前端
  // res.send("2323");
});

//7.修改用户信息
Router.put("/edit/:id", async (req, res) => {
  //req.params动态路由用来接收id；req.body 接收要修改的新数据
  // console.log(req.params, 111);
  // console.log(req.body, 222);
  let query = {
    _id: ObjectId(req.params.id),
  };
  console.log(query, 111);
  // console.log(req.body, 222);
  let result = {};
  try {
    let data = await mongo.update("users", query, req.body); //因为插入到数据库里面的数据必须是数组格式：arr是一个数组
    // console.log(data);
    result = data;
  } catch (err) {
    result = {
      code: 0,
      message: "服务器异常",
    };
  }
  // res.send("登录成功");
  res.send(result); //响应数据给前端
  // res.send("2323");
});


//3.获取分类信息
Router.get("/kind", async (req, res) => {
  let result = {};
  try {
    let data = await mongo.find("kinds", {}); //因为插入到数据库里面的数据必须是数组格式：arr是一个数组
    // console.log(data);
    result = data;
  } catch (err) {
    result = {
      code: 0,
      message: "服务器异常",
    };
  }
  // res.send("登录成功");
  res.send(result); //响应数据给前端
});

//3.获取商品信息
Router.get("/goodkind/:id", async (req, res) => {
  let query = {
    _id: ObjectId(req.params.id),
  };
  let result = {};
  try {
    let data = await mongo.find("goods2", query); //因为插入到数据库里面的数据必须是数组格式：arr是一个数组
    // console.log(data);
    result = data;
  } catch (err) {
    result = {
      code: 0,
      message: "服务器异常",
    };
  }
  // res.send("登录成功");
  res.send(result); //响应数据给前端
});

//1.小程序-添加订单接口
Router.post("/order", async (req, res) => {
  //post请求 body
  // console.log(req.body, 675);
  let arr = [];
  let result = {};
  req.body.status = 1;
  arr.push(req.body);
  // // console.log(arr,890);
  try {
    let data = await mongo.create("order", arr); //因为插入到数据库里面的数据必须是数组格式：arr是一个数组
    // console.log(data,789);
    if (data.code) {
      // let query = {username:req.body.username};
      // let res = await mongo.find("users", { findquery:  query});
      // console.log(res,666); 
      result = {
        code: 1,
        message: "订单添加成功",
        // uid : res.data[0]._id
      };
    } else {
      result = {
        code: 0,
        message: "订单添加失败",
      };
    }
  } catch (err) {
    result = {
      code: 0,
      message: "服务器异常",
    };
  }

  res.send(result); //响应数据给前端
});

//2.小程序-查询订单接口
Router.get("/orderList", async (req, res) => {
  //用户传：page:1 页码；pagesize:10;过来
  console.log(req.query, 123);
  let query = {
    uid: req.query.uid,
  };
  // console.log(query, 8990);
  let result = {};
  try {
    let data = await mongo.find("order", {
      findquery: query
    }); //因为插入到数据库里面的数据必须是数组格式：arr是一个数组
    // console.log(data, 890);
    result = data;
  } catch (err) {
    result = {
      code: 0,
      message: "服务器异常",
    };
  }
  // res.send("登录成功");
  res.send(result); //响应数据给前端
  // res.send("2323");
});

//封装代码，整理给前端的数据
function sendFE(openid, data, res) {
  //1.生成token
  let token = create(openid);
  //2.整理一个对象，准备发给前端
  let result = {
    code: 1,
    message: '微信小程序登陆成功',
    uid: data.data[0]._id,
    token: token
  }
  //3.发送数据给前端
  res.send(result);
}

//3.小程序微信登陆接口
Router.post("/wxlogin", async (req, res) => {
  // console.log(req.body); //存放前端发过来的数据
  //1.//获取前端传过来的code
  let {
    code
  } = req.body;
  //2.发送请求：把相关数据发给微信的服务器
  let url = 'https://api.weixin.qq.com/sns/jscode2session';
  let params = {
    appid: 'wx0cca6535d06b5f8d',
    secret: '94fdfac168538f504631efd1786fed29',
    js_code: code,
    grant_type: 'authorization_code'
  }
  //3.发送请求后，微信返回的数据，提交我们想要的 openid和session_key
  let resData = await axios.get(url, {
    params: params
  });
  //解构：openid和session_key
  // console.log(resData, 999)
  let {
    openid,
    session_key
  } = resData.data;
  // console.log('我们想要的数据1：', openid)
  // console.log('我们想要的数据2：', session_key)

  //3.1 判断用户表是否有这个openid==uid。没有：新增一个用户信息；有：响应前端
  let data = await mongo.find("users", {
    findquery: {
      openid
    }
  });
  // console.log('data是', data);
  if (data.code) {
    //查询成功：响应前端
    sendFE(openid,data,res);
  } else {
    //查询失败：没有：新增一个用户信息
    let arr = [];
    //用户信息
    let userinfo = {
      openid,
      session_key
    }
    arr.push(userinfo);
    let data = await mongo.create('users', arr);
    // console.log('数据添加结果', data);
    if (data.code) {
      //插入成功。查询数据，返回给前端
      let data = await mongo.find("users", {
        findquery: {
          openid
        }
      });
      if (data.code) {
        //查到数据，整理数据发给前端
        sendFE(openid,data,res);
      }

    }
  }


  // let result = {
  //   code: 1,
  //   message: '成功'
  // };
  // res.send(result); //把数据发送给前端
})

module.exports = Router;